package com.lam.common.utils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import com.lam.common.context.ContextHolder;

/**
 * spring工具类 
 * @author lam
 */
public final class SpringUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(SpringUtils.class);
	
	public static ApplicationContext getApplicationContext() {
		return ContextHolder.getApplicationContext();
	}
	
	public static BeanFactory getBeanFactory() {
		return ContextHolder.getBeanFactory();
	}
	
	/**
	 * 获取request
	 */
	public static HttpServletRequest getRequest() {
		return ContextHolder.getRequest();
	}

	/**
	 * 获取response
	 */
	public static HttpServletResponse getResponse() {
		return ContextHolder.getResponse();
	}
	
	/**
     * 从BeanFactory中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name, Class<T> clazz) {
    	if (StringUtils.isBlank(name) || clazz == null) {
    		return null;
    	}
        try {
            return getApplicationContext().getBean(name, clazz);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

	/**
	 * 从BeanFactory中取得名称为name的Bean, 自动转型为所赋值对象的类型
	 *
	 * @param name
	 * @return Object 一个以所给名字注册的bean的实例
	 * @throws org.springframework.beans.BeansException
	 *
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		if (StringUtils.isBlank(name)) {
    		return null;
    	}
		return (T) getBeanFactory().getBean(name);
	}

	/**
	 * 获取类型为requiredType的对象
	 * 从BeanFactory中取得类型为requiredType的Bean, 自动转型为所赋值对象的类型
	 *
	 * @param clz
	 * @return
	 * @throws org.springframework.beans.BeansException
	 *
	 */
	public static <T> T getBean(Class<T> clz) {
		
		return getBeanFactory().getBean(clz);
	}
	
	/**
	 * 如果BeanFactory包含一个与所给名称匹配的bean定义，则返回true
	 *
	 * @param name
	 * @return boolean
	 */
	public static boolean containsBean(String name) {
		return getBeanFactory().containsBean(name);
	}

	/**
	 * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
	 * 如果与给定名字相应的bean定义没有被找到，将会抛出一个异常（NoSuchBeanDefinitionException）
	 *
	 * @param name
	 * @return boolean
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 *
	 */
	public static boolean isSingleton(String name) {
		return getBeanFactory().isSingleton(name);
	}

	/**
	 * @param name
	 * @return Class 注册对象的类型
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 *
	 */
	public static Class<?> getType(String name) {
		return getBeanFactory().getType(name);
	}

	/**
	 * 如果给定的bean名字在bean定义中有别名，则返回这些别名
	 *
	 * @param name
	 * @return
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 *
	 */
	public static String[] getAliases(String name) {
		return getBeanFactory().getAliases(name);
	}

	/**
	 * 获取aop代理对象
	 * 
	 * @param invoker
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getAopProxy(T invoker) {
		return (T) AopContext.currentProxy();
	}

	/**
	 * 获取当前的环境配置，无配置返回null
	 *
	 * @return 当前的环境配置
	 */
	public static String[] getActiveProfiles() {
		return getApplicationContext().getEnvironment().getActiveProfiles();
	}

	/**
	 * 获取当前的环境配置，当有多个环境配置时，只获取第一个
	 *
	 * @return 当前的环境配置
	 */
	public static String getActiveProfile() {
		final String[] activeProfiles = getActiveProfiles();
		return CollectionUtil.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
	}
	
	/**
	 * 扫描指定 pattern 下的包名
	 * @param packagePattern
	 * @return
	 */
	public static List<String> scanPackage(String pattern) {
		List<Class<?>> list = scanClass(pattern);
		if(CollectionUtil.isEmpty(list)) {
			return Collections.emptyList();
		}
		Set<String> packageSet = new HashSet<>();
		for (Class<?> clazz : list) {
			packageSet.add(clazz.getPackage().getName());
		}
		return new ArrayList<>(packageSet);
	}
	
	/**
	 * 扫描指定 pattern 下的带有 annotationType 注解的类全名
	 * @param pattern
	 * @param annotationType
	 * @return
	 */
	public static List<String> scanClassName(String pattern, Class<? extends Annotation> annotationType) {
		
		List<Class<?>> list = scanClass(pattern, annotationType);
		if(CollectionUtil.isEmpty(list)) {
			return Collections.emptyList();
		}
		List<String> classList = new ArrayList<>();
		for (Class<?> clazz : list) {
			classList.add(clazz.getName());
		}
		return classList;
	}
	
	/**
	 * 扫描指定 pattern 下的带有 annotationType 注解的类
	 * @param pattern
	 * @param annotationType
	 * @return
	 */
	public static List<Class<?>> scanClass(String pattern, Class<? extends Annotation> annotationType) {
		
		List<Class<?>> list = scanClass(pattern);
		if(CollectionUtil.isEmpty(list)) {
			return list;
		}
		List<Class<?>> classList = new ArrayList<>();
		for (Class<?> clazz : list) {
			if(AnnotationUtils.isAnnotationDeclaredLocally(annotationType, clazz)) {
				classList.add(clazz);
			}
		}
		return classList;
	}
	
	/**
	 * 扫描指定 pattern 下的类
	 * @param pattern
	 * @return 
	 */
	public static List<Class<?>> scanClass(String pattern) {
		
    	if(StringUtils.isBlank(pattern)) {
    		return Collections.emptyList();
    	}
    	
    	if(!pattern.contains("classpath")) {
    		pattern = pattern.contains(".") ? ClassUtils.convertClassNameToResourcePath(pattern) : pattern;
    		pattern = String.format("classpath*:%s/**/*.class", pattern);
    	}
    	
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
		Set<Class<?>> classSet = new HashSet<>();
		try {
			Resource[] resources = resolver.getResources(pattern);
			if (CollectionUtil.isEmpty(resources)) {
				return Collections.emptyList();
			}
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					try {
						classSet.add(Class.forName(metadataReaderFactory.getMetadataReader(resource).getClassMetadata().getClassName()));
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return new ArrayList<>(classSet);
	}
}
